package org.springblade.modules.repair.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tenant.annotation.TenantIgnore;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringPool;
import org.springblade.modules.repair.entity.ElevatorPartsStructureTemplateRelation;
import org.springblade.modules.repair.service.IElevatorPartsStructureTemplateRelationService;
import org.springblade.modules.repair.vo.MaintainPartsTreeVO;
import org.springblade.modules.repair.vo.MaintainPartsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springblade.modules.repair.entity.MaintainParts;
import org.springblade.modules.repair.mapper.MaintainPartsMapper;
import org.springblade.modules.repair.service.MaintainPartsService;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MaintainPartsServiceImpl extends BaseServiceImpl<MaintainPartsMapper, MaintainParts> implements MaintainPartsService{

	@Autowired
	private IElevatorPartsStructureTemplateRelationService elevatorPartsStructureTemplateRelationService;

	@Override
	public List<MaintainPartsVO> partsList(MaintainParts maintainParts) {
		return baseMapper.partsList(maintainParts);
	}

	@Override
	public List<MaintainPartsTreeVO> partsTree(MaintainParts maintainParts) {
		return baseMapper.partsTree(maintainParts);
	}

	@Override
	public List<MaintainPartsTreeVO> getElevatorStructureTree(Long elevatorId) {
		ElevatorPartsStructureTemplateRelation templateRelation = elevatorPartsStructureTemplateRelationService.getOne(Wrappers.<ElevatorPartsStructureTemplateRelation>lambdaQuery().eq(ElevatorPartsStructureTemplateRelation :: getElevatorId, elevatorId), false);
		if (Func.isEmpty(templateRelation) || Func.isEmpty(templateRelation.getCategoryArrIds())) {
			return new ArrayList<>();
		}

		List<MaintainPartsTreeVO> childList = baseMapper.getPartsChildList(templateRelation.getCategoryArrIds(), elevatorId);
		// 父节点id集合
		Set<String> parentIds = childList.stream().map(MaintainPartsTreeVO::getAncestors).flatMap(t -> Arrays.stream(t.split(StringPool.COMMA))).collect(Collectors.toSet());
		List<MaintainPartsTreeVO> parentList = baseMapper.getPartsParentByIds(parentIds, elevatorId);

		// childList+parentList两个集合合并，并去重
		childList.addAll(parentList);
		return childList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MaintainPartsTreeVO::getId))), ArrayList::new));
	}
}
